import 'package:flutter/material.dart';

class FormDemo extends StatefulWidget {
  @override
  _FormState createState() => _FormState();
}

class _FormState extends State<FormDemo> {
  TextEditingController _unameController = TextEditingController();
  TextEditingController _upwdController = TextEditingController();
  GlobalKey _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false, //为false时，在软键盘弹出时不会触发调整整体大小
        appBar: AppBar(
          title: Text('表单示例'),
        ),
        body: SingleChildScrollView(
          child: ConstrainedBox(
          constraints: BoxConstraints(minHeight: 300),
          child: Padding(
            padding:
                const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24.0),
            child: Form(
              key: _formKey, //设置globalKey，用于后面获取FormState
              autovalidateMode: AutovalidateMode.always, //开启自动校验
              child: Column(
                children: <Widget>[
                  TextFormField(
                    controller: _unameController,
                    keyboardType: TextInputType.emailAddress,
                    cursorColor: Theme.of(context).accentColor,
                    decoration: InputDecoration(
                      labelText: '用户名',
                      hintText: '用户名或邮箱',
                      icon: Icon(Icons.person),
                    ),
                    validator: (value) =>
                        value.trim().length > 0 ? null : '用户名不能为空',
                  ),
                  TextFormField(
                    controller: _upwdController,
                    keyboardType: TextInputType.number,
                    cursorColor: Theme.of(context).accentColor,
                    decoration: InputDecoration(
                      labelText: '密码',
                      hintText: '请输入密码',
                      icon: Icon(Icons.lock),
                    ),
                    obscureText: true,
                    validator: (value) =>
                        value.trim().length > 5 ? null : '密码不能少于6位',
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 28.0),
                    child: Row(
                      children: <Widget>[
                        Expanded(
                            child: ElevatedButton(
                                child: Text('登录'),
                                style: ElevatedButton.styleFrom(
                                  onPrimary: Colors.white,
                                  padding: const EdgeInsets.symmetric(vertical: 15.0),
                                  primary: Theme.of(context).primaryColor,
                                ),
                                onPressed: () {
                                  // 在这里不能通过此方式获取FormState，context不对
                                  // print(Form.of(context));
                                  // 此处的context为FormDemo的context，
                                  // 而Form.of(context)是根据所指定context向根去查找，
                                  // 而FormState是在FormDemo的子树中，所以不行.
                                  // 正确的做法是通过Builder来构建登录按钮，
                                  // Builder会将widget节点的context作为回调参数

                                  // 通过_formKey.currentState 获取FormState后，
                                  // 调用validate()方法校验用户名密码是否合法，校验
                                  // 通过后再提交数据。
                                  if ((_formKey.currentState as FormState)
                                      .validate()) {
                                    //验证通过提交数据
                                    print('验证通过');
                                  }
                                }
                            )
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 28.0),
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          child: Builder(
                            builder: (ctx) => ElevatedButton(
                                child: Text('登录'),
                                style: ElevatedButton.styleFrom(
                                  // 设置字体颜色
                                  onPrimary: Colors.black87,
                                  padding: const EdgeInsets.symmetric(vertical: 15.0),
                                  primary: Theme.of(context).primaryColor,
                                  textStyle: TextStyle(
                                      fontSize: 15.0
                                  ),
                                ),
                                onPressed: () {
                                  // 通过Builder来构建登录按钮，
                                  // Builder会将FormState节点的context作为回调参数
                                  // 由于本widget也是Form的子代widget，所以可以通过下面方式获取FormState
                                  if (Form.of(ctx).validate()) {
                                    //验证通过提交数据
                                    print('验证通过');
                                  }
                                }),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        )
        )
    );
  }
}
